package de.herberlin.webapp.db;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class EntityManagerListener implements ServletRequestListener {

	private static Log logger = LogFactory.getLog(EntityManagerListener.class);

	public void requestDestroyed(ServletRequestEvent req) {

		EntityManager em = emTl.get();
		if (logger.isDebugEnabled()) {
			logger.debug("Destroying EntityManager: " + em);
		}
		if (em != null) {
			em.close();
			emTl.remove();
		}
	}

	public void requestInitialized(ServletRequestEvent req) {
	}

	private static EntityManagerFactory emf = Persistence
			.createEntityManagerFactory("datasource");
	private static ThreadLocal<EntityManager> emTl = new ThreadLocal<EntityManager>() {
		@Override
		protected synchronized EntityManager initialValue() {
			EntityManager em = emf.createEntityManager();
			if (logger.isDebugEnabled()) {
				logger.debug("EntityManager created: " + em);
			}
			return em;
		};
	};

	/**
	 * Creates the ThreadLocal entity manager and returns it
	 * 
	 * @return
	 */
	public static EntityManager getEntityManager() {
		EntityManager em = emTl.get();
		if (logger.isDebugEnabled()) {
			logger.debug("Returning: " + em);
		}
		return em;
	}
}
